/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,Button,Image,TouchableOpacity,Switch,ScrollView} from 'react-native';
import Printer,{Event} from '../../utils/printer';
import SwiperCard,{Event as CardEvent} from '../../utils/swipercard';
import UsaPay,{Event as PayEvent} from '../../utils/usapay';
import FetchBlod from '../../utils/downImgUtils';
import {scaleSize} from '../../utils/screen'
import ViewShot,{ captureRef } from "react-native-view-shot";
import FontText from '../components/FontText'
import FS from 'rn-fetch-blob';
import ImagePicker from 'react-native-image-crop-picker';
export default class Test extends Component {

  constructor(props){
    super(props);
    this.state = {
      imgs:[],
      printers:[],
      isCash:true
    }
  }
  componentWillMount(){
    console.log("test")
    this.listner = Event.addListener("printerEvent",(e)=>this.printerEvent(e))
    this.swiperListner = CardEvent.addListener("onDataReceived",(e)=>this.swiperCardEvent(e))
    this.payEventListner = PayEvent.addListener("usaPayEvent",(e)=>{this.usaPayEvent(e)})
  }
  printerEvent(e){
    console.log(e);
  }
  swiperCardEvent(e){
    console.log(e);
  }
  usaPayEvent(e){
    console.log(e);
  }
  downImgs(){
    FetchBlod(["https://zafgoos.oss-cn-shanghai.aliyuncs.com/service/goods/main/Image_679546386387023332_1529553853848.jpg","https://zafgoos.oss-cn-shanghai.aliyuncs.com/service/goodsShelves/Image_6757262518283961192_1528191791532.jpg","https://zafgoos.oss-cn-shanghai.aliyuncs.com/service/goods/main/Image_4491730398584154151_1526523973335.jpg"],(path,index)=>{
      let list = this.state.imgs;
      list.push(path);
      this.setState({
        imgs:list
      })
    });
  }
  componentWillUnmount(){
    console.log(this.listner)
    this.listner && this.listner.remove();
  }
  onCapture = uri => {
    console.log("do something with ", uri);
  }
  onPreview(){
    ImagePicker.openPicker({
      compressImageMaxWidth: 640,
      compressImageMaxHeight: 640,
      cropping: true,
      mediaType:"photo",
      includeBase64:true,
      compressImageQuality:0.8,
    }).then(image => {
      console.log(image);
    });
  }
  render() {
    let {imgs,printers,isCash} = this.state;
    return (
      <View style={styles.container}>
          <View style = {{height:0,width:scaleSize(576)}}>
            <ScrollView ref = "test" >
              <View style = {{justifyContent:"center",alignItems:"center"}}>
              <FontText font = {'book'} style = {{fontWeight: 'bold',fontSize: 40}}>Menu</FontText>
              <FontText font = {'book'}>Menu ------> 👋 </FontText>
              <FontText font = {'book'}>Table ------> 😊 </FontText>
              <FontText font = {'book'}>Register ------> 🔥 </FontText>
              <FontText font = {'book'}>CashDrawer ------> 🔥 </FontText>
              <FontText font = {'book'}>Self Ording ------> 🔥 </FontText>
              <FontText font = {'book'}>Report ------> 🔥 </FontText>
              <View style = {{width:50,height:50,borderColor:1,borderRadius:50,borderWidth:2}}></View>
              <View style = {{width:50,height:50,borderColor:1,borderWidth:2}}></View>
              <FontText font = {'book'}>Printer ------> 🔥 </FontText>
              <FontText font = {'book'}>Cash ------> 🔥 </FontText>
              <FontText font = {'book'}>Time ------> 🔥 </FontText>
              <FontText font = {'book'}>👋😊😢⬆️🦐9⃣️🔥🍇🌰👌👋💔</FontText>
              </View>
          </ScrollView>
          </View>
        <View>
          <Switch value={isCash} onValueChange = {(val)=>this.setState({isCash:val})} ></Switch>
          <Text>{isCash?"cash":"printer"}</Text>
        </View>
        <View>
          <Text>----swiper-card----</Text>
          <TouchableOpacity
            style = {styles.btn}
            onPress = {()=>this.initSwiperCard()}
            >
            <Text>init</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style = {styles.btn}
            onPress = {()=>this.connetSwiperCard()}
            >
            <Text>connet</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style = {styles.btn}
            onPress = {()=>this.onPreview()}
            >
            <Text>Preview</Text>
          </TouchableOpacity>
        </View>
        <View>
          <Text>----usapay-post----</Text>
          <TouchableOpacity
            style = {styles.btn}
            onPress = {()=>this.initPos()}
            >
            <Text>init</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style = {styles.btn}
            onPress = {()=>this.transction()}
            >
            <Text>transction</Text>
          </TouchableOpacity>
        </View>
        <Button onPress = {()=>this.searchPrinter()} title = "searchPrinter"></Button>
        <Button onPress = {()=>this.priter()} title = "testPriter"></Button>
        <Button onPress = {()=>this.captchPrinter()} title = "testPriter"></Button>
        <Button onPress = {()=>this.downImgs()} title = "downloadImgs"></Button>
        {
          imgs.map((item)=>{
           return (
            <View>
              <Text>{item}</Text>
              <Image style = {{width:100,height:100}} source={{uri:item}} />
            </View>
           )
          })
        }
        
        {
          printers.map((item)=>{
            return(
              <TouchableOpacity
              activeOpacity = {0.8}
              style = {styles.item}
              onPress = {()=>this.connect(item)}
            >
              <Text>{item.modelName}</Text>
              <Text>{item.portName}</Text>
              <Text>{item.macAddress}</Text>
            </TouchableOpacity>
            )
          })
        }

      </View>
    );
  }
  captchPrinter(){
    // this.refs.viewShot.capture().then(uri => {
    //   console.log("data:image/png;base64,"+ uri);
    // })
    captureRef(this.refs.test, {
      format: 'png',
      quality: 0.1,
      snapshotContentContainer: true,
      width:576
    })
    .then(path =>{
      Printer.send({portName:"xx",path:path},(err,res)=>{
        //删除文件
        FS.fs.unlink(path)
      })
    })
  }
  initSwiperCard(){
    SwiperCard.initial();
  }
  connetSwiperCard(){
    SwiperCard.connect((data) => {
      const { isDeviceConnected, isDeviceOpened } = data;
      console.log(isDeviceConnected, isDeviceOpened)
      if (isDeviceConnected && isDeviceOpened) {
        console.log("Card reader is connected and ready!!!");
      }
    });
  }
  disconnetSwiperCard(){
    SwiperCard.disconnect();
  }
  clearSwiperCard(){
    SwiperCard.clearData();
  }
  priter(){
    //test
    Printer.send({portName:"xx"},(err,res)=>{
      console.log(err,res);
    })
  }
  initPos(){
    UsaPay.initial({
      currentMode:"sandbox",
      sourceKey:"_iOunDQQLRKNta66hjJhfBNiD1WU6EV7",
      pinNum:"123456",
      enableDebugLog:true
    })
  }
  transction(){
    UsaPay.transction({
      command:"cc:sale",
      amount:"0.10",
      invoice:"10000",
      description:"My module transction!"
    },(err)=>{
      console.log(err);
    })
  }
  connect(item){
    console.log(item);
    let {isCash} = this.state;
    if(isCash){
      Printer.openCash({portName:item.portName,channel:1},(err,res)=>{
        console.log(err,res);
      })
    }else{
      Printer.send({portName:item.portName},(err,res)=>{
        console.log(err,res);
      })
    }
  }
  searchPrinter(){
      console.log(Printer)
    Printer.search("TCP:",(err,list)=>{
        if(!err){
          this.setState({
            printers:list
          })
        }
    });
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  item:{
    backgroundColor: "blue",
    margin: 10,
  },
  btn:{
    padding: 10,
    backgroundColor: "red"
  }
});
